﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Utilities
{
    public class ImgUpload
    {
        static HttpRequest Request { get; set; }
        static HttpResponse Response { get; set; }
        //更新图片
        public static string UploadImage(string WenJianJia)
        {
            Request = HttpContext.Current.Request;
            Response = HttpContext.Current.Response;
            string retVal = string.Empty;
            try
            {
                var files = Request.Files;
                if (files != null && files.Count > 0)
                {
                    HttpPostedFile file = Request.Files["Filedata"];//接收文件数据.
                    string fileName = Path.GetFileName(file.FileName);//获取文件名称.
                    string fileExt = Path.GetExtension(fileName);//文件扩展名.
                    string fullDir = "";
                    try
                    {
                        DateTime data = System.DateTime.Now;
                        //file.SaveAs(Request.MapPath("/UploadImage/"+fileName));
                        string dir = WenJianJia;
                        Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(dir)));//创建文件夹.
                        //string fullDir = dir + Common.WebCommon.GetStreamMD5(file.InputStream) + fileExt;//构建完整路径，完成文件重命名
                        fullDir = Request.MapPath(dir + string.Format("{0:yyyyMMddhhmmss}", data) + fileExt);
                        file.SaveAs(fullDir);//保留原图.
                        string fileNames = dir + string.Format("{0:yyyyMMddhhmmss}", data) + fileExt;
                        Response.Write("{\"file\":\"" + fileNames + "\",\"success\":\"true\"}");
                        retVal = fileNames;
                        //userService.UpdateLogo(fileNames,(int)user.Id);
                    }
                    catch (Exception)
                    {

                        Response.Write("\"file\":\"" + fullDir + "\",\"success\":\"false\"");
                        retVal = "false";
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                retVal = "false";
            }
            return retVal;
        }
    }
}
